package com.atguigu.srb.oss.controller.api;

import com.atguigu.common.exception.BusinessException;
import com.atguigu.common.result.R;
import com.atguigu.common.result.ResponseEnum;
import com.atguigu.srb.oss.service.FileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author: Luckyh
 * @date : 2022/2/25 20:03
 */
@Api(tags = "文件管理系统")
@CrossOrigin
@RestController
@RequestMapping("/api/oss/file")
public class FileController {

    @Resource
    private FileService fileService;

    @ApiOperation(value ="文件上传")
    @PostMapping("/upload")
    public R updloader(
            @ApiParam(value = "文件",required = true)
            @RequestParam("file") MultipartFile file,

            @ApiParam(value = "模块",required = true)
            @RequestParam("module") String module
            ){

        InputStream inputStream = null;
        try {
            inputStream = file.getInputStream();
        } catch (IOException e) {
            throw new BusinessException(ResponseEnum.UPLOAD_ERROR);
        }
        // 原始文件名字
        String originalFilename = file.getOriginalFilename();
        String url = fileService.uploadFile(inputStream, module, originalFilename);


        return R.ok().message("文件上传成功").data("url", url);

    }


    @ApiOperation(value = "文件删除")
    @DeleteMapping("/delete")
    public R remove(
            @ApiParam(value = "要删除的文件名",required = true)
            @RequestParam("url") String url
    ){

        fileService.removeFile(url);

        return R.ok().message("文件删除成功");
    }


}
